using MediatR;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;
using TerritoryGame.Domain.ValueObjects;

namespace TerritoryGame.Application.Handlers;

public class CreateGameCommandHandler : IRequestHandler<CreateGameCommand, CreateGameResult>
{
    private readonly IGameRepository _gameRepository;

    public CreateGameCommandHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }

    public async Task<CreateGameResult> Handle(CreateGameCommand request, CancellationToken cancellationToken)
    {
        // Generate room code (simple implementation)
        var roomCode = GenerateRoomCode();
        
        // Create game using constructor
        var gameId = GameId.New();
        var game = new Game(gameId, request.Name, request.Duration);
        
        // Create and add owner player
        var playerId = PlayerId.New();
        var ownerPlayer = new Player(playerId, request.OwnerNickname, true);
        game.AddPlayer(ownerPlayer);

        // Save to database
        await _gameRepository.AddAsync(game);

        return new CreateGameResult
        {
            GameId = game.Id,
            RoomCode = roomCode
        };
    }

    private static string GenerateRoomCode()
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        return new string(Enumerable.Repeat(chars, 6)
            .Select(s => s[random.Next(s.Length)]).ToArray());
    }
}
